<template>
	<view class="body">
		<myHead :title="title" />
		<scroll-view scroll-y="true" class="scroll-Y sv" :style="'{height:'+navHeight+'px}'">
			<uni-forms style="margin-top: 5%;" :value="addMeeting" ref="form" :rules="rules">
				<uni-forms-item label="会议名称" name="meetingName" :required="true">
					<uni-easyinput :required="true" type="text" v-model="addMeeting.meetingName" placeholder="请输入会议名称" />
				</uni-forms-item>
				<uni-forms-item name="meetingTheme" label="会议主题" :required="true">
					<uni-easyinput :required="true" type="text"  v-model="addMeeting.meetingTheme"
						placeholder="请输入会议主题" />
				</uni-forms-item>
				<uni-forms-item name="meetDescri" label="会议时间"  class="picker">
					  <picker mode="date" :value="addMeeting.date"
					   @change="bindDateChange">
					        <view class="uni-input">{{addMeeting.date}}</view>
					   </picker>
				</uni-forms-item>
				<uni-forms-item name="meetDescri" label="截至时间"  class="picker">
					  <picker mode="date" :value="addMeeting.endTime"  :limit="5-img.length" 
					   @change="bindDateChange1">
					        <view class="uni-input">{{addMeeting.endTime}}</view>
					   </picker>
				</uni-forms-item>
				<uni-forms-item name="meetingRoom" :required="true" label="会议地点">
					<uni-easyinput required="true" type="test" v-model="addMeeting.meetingRoom"
						placeholder="请输入会议地点" />
				</uni-forms-item>
				<uni-forms-item label="会议文件" name="filesupload">
					<uni-file-picker 
					    v-model="filesupload" 
						ref="files"
					    fileMediatype="all" 
						:auto-upload="false"
					    mode="grid" 
					    @select="select" 
					    @delete="progress" 
					    @success="success" 
					/>
					<!-- <view><span>文件数量</span><span style="float: right;">{{filesupload.length}}/5</span></view>
					<view>
						<uni-grid :column="6" class="files" @change="filesclick">
							<uni-grid-item class="header">
								<span>+</span>
							</uni-grid-item>
							<uni-grid-item class="content" v-if="filesupload.length>0">
								<view v-for="(item,key) in filesupload" :key="key">
									<span class="text" style="width: 60%;">
										{{item.fileName.substr(0,12)}}
									</span>
									<span style="float: right; width: 10%"
										@click.stop="filesupload.splice(key,1)">×</span>
								</view>
							</uni-grid-item>
						</uni-grid>
					</view> -->
				</uni-forms-item>
				<uni-forms-item name="taskList">
					<button type="primary" @click="gotoTask" size="mini">添加</button>
					<button type="warn" size="mini" @click="taskList.pop()">移除</button>
					<uni-table border stripe emptyText="暂无更多数据">
						<!-- 表头行 -->
						<uni-tr>
							<uni-th align="left">任务名称</uni-th>
							<uni-th align="left">执行人</uni-th>
							<uni-th align="left">监督人</uni-th>
							<uni-th align="left">分数</uni-th>
						</uni-tr>
						<uni-tr v-for="(item,index) in taskList" :key="index">
							<uni-th align="left">{{item.taskName}}</uni-th>
							<uni-th align="left">{{item.executorUser.userName}}</uni-th>
							<uni-th align="left">{{item.monitorUser.userName}}</uni-th>
							<uni-th align="left">{{item.number}}</uni-th>
						</uni-tr>
					</uni-table>
				</uni-forms-item>

			</uni-forms>
		</scroll-view>

		<button @click="submitForm">提交</button>
		<button @click="restDate()">重置</button>
	</view>
</template>

<script>
	import myHeader from '../components/head.vue'
	import {
		uploadMultipleFile,
		uploadFile
	} from '../../api/api_files.js'
	import {
		getGroupUser,
		addMeetingByGroup,
		checkMeetingByLeader,
		getMeetingByGroup,
		getMeetingByLeader
	}
	from '../../api/api_party_meeting.js'
	export default {
		data() {
			return {
				rules:{
					meetingName:{
						rules:[{errorMessage: '请输入姓名', required: true,},],
						},
					meetingTheme:{
						rules:[{errorMessage: '请输入主题', required: true,},],
						},
					meetingRoom:{
						rules:[{errorMessage: '请输入地点', required: true,},],
						},
						}
							,
				roleCode: "",
				pH: 0, //窗口高度
				navHeight: 0, //元素的所需高度
				title: "新增会议纪要",
				userList: [],
				filesupload: [],
				img:[],
				addMeeting: { //新增会议
					meetingName: '', //会议标题
					createUser: '', //创建人
					meetGroup: '', //会议组
					meetingFile: [], //会议文件
					collectFile: '',
					meetDescri: '',
					createTime: '',
					date:'',
					endTime:'',
					meetingTheme:'',
					meetingRoom:''
				},
				taskList: [],
				filesDetails: {
					listStyles: {
						"borderStyle": {
							"color": "#eee", // 边框颜色
							"width": "1px", // 边框宽度
							"style": "solid", // 边框样式
							"radius": "5px" // 边框圆角，不支持百分比
						},
						"border": false, // 是否显示边框
						"dividline": true // 是否显示分隔线
					},
					imageStyles: {
						"height": 60, // 边框高度
						"width": 60, // 边框宽度
						"border": { // 如果为 Boolean 值，可以控制边框显示与否
							"color": "#eee", // 边框颜色
							"width": "1px", // 边框宽度
							"style": "solid", // 边框样式
							"radius": "50%" // 边框圆角，支持百分比
						}
					}

				},
				extension1: ['doc', 'pdf', 'docx', 'doc'],
				extension: ['doc', 'pdf', 'docx', 'doc', 'png', 'jpg', 'jpeg'],
				addTasks: [{
					taskName: '',
					createUser: '',
					executorUser: '',
					taskScore: '',
					monitorUser: '',
					taskCreateTime: '',
				}]
			}
		},
		computed:{
		},
		components: {
			myHead: myHeader,
		},
		methods: {
			restDate() {
				this.addMeeting = { //新增会议
					meetingName: '', //会议标题
					createUser: '', //创建人
					meetGroup: '', //会议组
					meetingFile: [], //会议文件
					collectFile: '',
					meetDescri: '',
					createTime: '',
					date:'',
					endTime:'',
					meetingTheme:'',
					meetingRoom:'',
					"groupCode":this.addMeeting.groupCode
				}
				this.filesupload = [];
				this.taskList = [];
			},
			 bindDateChange(e) {
			            this.addMeeting.date = e.target.value
			        },
			 bindDateChange1(e) {
			            this.addMeeting.endTime = e.target.value
			        },
			gotoTask() {
				uni.navigateTo({
					url: `./addMeetingTask?executors=${JSON.stringify(this.userList.executors)}&monitors=${JSON.stringify(this.userList.monitors)}`
				})
			},
			success(e){
				console.log(this.filesupload)
			},
			select(e){
				console.log(e)
				let _this = this
				let temp = e.tempFiles.filter(res=> {
					return this.extension.indexOf(res.extname)<0
				})
				if(temp.length>0){//判断是否可上传
					return uni.showToast({
						title:"请不要上传出图片、dpf、word之外的文件",
						duration:2000,
						icon:'none',
						success: () => {
							_this.img = [],
							_this.filesupload = []
						}
					})
				}
				let token = uni.getStorageSync('AuthToken')
				e.tempFiles.forEach((source,index)=>{
					
					uni.uploadFile({
						url: '/api/uploadFile', //仅为示例，非真实的接口地址
						filePath: e.tempFilePaths[index],
						name: 'file',
						header: {
							'x-access-token': token
						},
						formData: {
							'name': source.name,
							'size': source.size
						},
						success: (res) => {
							let a = JSON.parse(res.data).data;
							_this.img.push({
								id:a.id,
								fileName:a.fileName
							})
							console.log(JSON.parse(res.data).data)
						},
						fail: () => {
								uni.showToast({
									title:'文件上传失败',
									duration:2000,
									icon:'none'
								})
						}
					});
				})
			} ,
			progress(e){//删除
			console.log(e)
			let name =  e.tempFile.name
				let files = this.img.filter(e=>e.fileName==name); 
				let index = this.img.indexOf(files[0])
				this.img.splice(index, 1); 
			} ,
			fail(e){
				console.log("@fail",e)
			} ,
			submitForm() {
				this.$refs.form.submit().then(res=>{
				if (this.taskList.length>0) {
					let _this = this;
					uni.showModal({
						title: '提示',
						content: '是否确定提交本次会议纪要？',
						success: function(res) {
							if (res.confirm) {
								// let parmas = [];
								// console.log(res)
								// _this.img.forEach((e, index) => {
								// 	parmas.push({
								// 		name: "files",
								// 		file: e.file,
								// 		url: e.url,
								// 	})
								// })
								// let token = uni.getStorageSync("AuthToken");
								// uni.uploadFile({
								// 	url: '/api/uploadMultipleFiles', //仅为示例，非真实的接口地址
								// 	name: 'files',
								// 	files: parmas,
								// 	header: {
								// 		'x-access-token': token
								// 	},
								// 	success: (uploadFileRes) => {
								// 		console.log('uploadFileRes',uploadFileRes)
								// 		console.log(JSON.parse(uploadFileRes.data).data)
								// 		_this.filesupload.push(...(JSON.parse(uploadFileRes.data).data)) //添加
								// 	},
								// 	fail: res => {
								// 		console.log(res)
								// 	}
								// });
								let parma = {
									"createUser": '',
									"judgeUser": '',
									"meetDescri": _this.addMeeting.meetDescri,
									"meetingFile":[],
									"meetingName": _this.addMeeting.meetingName,
									"tasks": [],
									'collectFile': _this.addMeeting.collectFile,
									'meetDescri': _this.addMeeting.meetDescri,
									'createTime': _this.addMeeting.createTime,
									'endTime':_this.addMeeting.endTime+" 00:00:00",
									'meetingTheme':_this.addMeeting.meetingTheme,
									'meetingRoom':_this.addMeeting.meetingRoom,
									"groupCode":_this.addMeeting.groupCode
								}
								let fileids =  _this.img.map(res=> res.id)
								// _this.filesupload.forEach(file=>{
								// 	fileids.push(file.id)
								// })
									parma.meetingFile = fileids.toString()
								_this.taskList.forEach(task => {//任务
									parma.tasks.push({
										taskName:task.taskName,
										executorUser:task.executorUser.userId,
										monitorUser:task.monitorUser.userId,
										taskScore:task.number
									})
								})
								parma.createUser = JSON.parse(localStorage.getItem('user')).data.userId
								console.log(parma)
								addMeetingByGroup(parma).then(res=>{
									uni.showToast({
										title:"新增会议成功",
										icon:'success',
										duration:2000,
										success:()=>{
											_this.restDate();
											uni.navigateBack()
										}
									})
								})
							} else if (res.cancel) {}
						}
					});
				} else {
					uni.showToast({
						title: "请正确填写会议标题、说明和任务表",
						duration: 2000,
						icon: 'none'
					})
				}
				
				})
			},
			filesclick() {
				let _this = this
				uni.chooseFile({
					count: 5 - _this.filesupload.length, //默认100
					extension: ['.doc', '.pdf', '.docx', '.doc', '.png', '.jpg', '.jpeg'],
					success: function(res) {
						let parma = [];
						console.log(res)
						res.tempFilePaths.forEach((e, index) => {
							parma.push({
								name: "files",
								file: res.tempFiles[index],
								url: e,
							})
						})
						console.log(parma)
						let token = uni.getStorageSync("AuthToken");
						uni.uploadFile({
							url: '/api/uploadMultipleFiles', //仅为示例，非真实的接口地址
							name: 'files',
							files: parma,
							header: {
								'x-access-token': token
							},
							success: (uploadFileRes) => {
								console.log(JSON.parse(uploadFileRes.data).data)
								_this.filesupload.push(...(JSON.parse(uploadFileRes.data)
									.data)) //添加
							},
							fail: res => {
								console.log(res)
							}
						});
					}
				})
			}, 
			 getDate(type) {
			            const date = new Date();
			            let year = date.getFullYear();
			            let month = date.getMonth() + 1;
			            let day = date.getDate();
			
			            if (type === 'start') {
			                year = year - 60;
			            } else if (type === 'end') {
			                year = year + 2;
			            }
			            month = month > 9 ? month : '0' + month;;
			            day = day > 9 ? day : '0' + day;
			            return `${year}-${month}-${day}`;
			        },
		},
		onLoad(e) {
			/**
			 * 安全 4 质量5 监督 6
			 * group 0：监督小组 1：质量小组 2：安全小组
			 */
			this.roleCode = JSON.parse(e.roleCode)
			
			console.log(this.roleCode)
			if(this.roleCode === 4){
				this.addMeeting.groupCode = 2
			}else if(this.roleCode === 5){
				this.addMeeting.groupCode = 1
			}
			let nowDate = new Date();
			let year = nowDate.getFullYear();
			let month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
			          : nowDate.getMonth() + 1;
			let day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
			          .getDate();
			this.addMeeting.date= year + "-" + month + "-" + day;  // "2018-03-26""
			this.addMeeting.endTime = this.addMeeting.date
		},onReady() {
			let sysHeight = uni.getSystemInfoSync().windowHeight;  //动态高度
			this.navHeight = sysHeight * 0.8;
			console.log("sysHeight:" + this.style)
			let that = this
			uni.getSystemInfo({
				success: function(res) { // res - 各种参数
					console.log(res.windowHeight); // 屏幕的宽度
					let info = uni.createSelectorQuery().select(".scroll-Y"); // 获取某个元素
					info.boundingClientRect(function(data) { //data - 各种参数
						console.log(data.height) // 获取元素宽度
						let view = res.windowHeight - data.height
						that.heightHome = view
					}).exec()
				}
			});
			/**
			 * 加载用户
			 */
			getGroupUser({
				roleId: this.roleCode
			}).then(res => {
				this.userList.executors = res;
			})
			getGroupUser({
				roleId: 6
			}).then(res => {
				this.userList.monitors = res;
			})

		},
	}
</script>
<style lang="scss" scoped>
	/**
	 * 定义按钮样式
	 */
	@mixin button-commit {
		background: linear-gradient(180deg, #ff5e59, #e20909);
		color: #fff;
	}

	.body {
		/deep/ .scroll-Y {
			width: 90%;
			margin: 0 auto;
		}
		
		/deep/ .picker{
			.uni-forms-item__content{
				border: 1px solid #e5e5e5;
				border-radius: 4px;
			}
			uni-picker{
				padding: 10px;
			}
		}

		>/deep/ button {
			@include button-commit;
			// position:fix;
			// button:0;
			width: 90%;
			margin: 2% auto;
		}

		/deep/ .uni-table {
			min-width: 0 !important;
		}

		/deep/ .uni-grid-wrap {
			border: transparent;
			height: auto !important;

			.header {
				height: auto !important;
				min-height: 44px;
				background-color: #f8f8f8;
				position: relative;

				span {
					position: absolute;
					text-align: center;
					top: 25%;
					left: 35%;
				}
			}

			.content {
				height: auto !important;
				text-overflow: ellipsis;
				white-space: nowrap;
				width: 80% !important;
				height: 44px;
				margin-left: 5px;
				border-left: 1px rgb(229, 229, 229) solid;
				border: transparent;

				.uni-grid-item__box {
					border: transparent;
				}

				uni-view {
					background-color: #f9f9f9;

					span {
						text-align: left;
						display: inline-block;
						overflow: hidden;
					}

				}
				
			}
		}
	}
</style>
